package rpt

import (
	"context"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/rest"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/go-log"
	"io"
	"os"
	"time"
)

func DownloadRptFile(ctx context.Context) {

	for {
		select {
		case <-ctx.Done():
			return
		case <-time.After(time.Second * 60):
			download(ctx)
		}
	}
}

func download(_ context.Context) {
	var err error
	var list []db.AmazonRpt
	_, err = app.GetOrm().Context.
		QueryTable(new(db.AmazonRpt)).
		Filter("Status", db.RptStatusGenCompleted).
		OrderBy("mtime").Limit(1).All(&list)
	if err != nil {
		log.Info("get downloadable rpt list failed")
		log.Info(err)
		return
	}
	if len(list) == 0 {
		//log.Info("no downloadable rpt")
		return
	}

	var rpt = list[0]
	var saveTo = rpt.GetTempFileName()
	log.Info("download rpt %s, file: %s, save_to: %s", rpt.RptId, rpt.RptFileUrl, saveTo)
	f, err := os.OpenFile(saveTo, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
	if err != nil {
		log.Info("open file %s failed", saveTo)
		log.Info(err) // 不更新数据库
		return
	}
	// download file
	err = rest.NewRequest(rpt.RptFileUrl, true).Download(func(totalSize int64, reader io.Reader) {
		_, e := io.Copy(f, reader)
		if e != nil {
			log.Info("save rpt file failed")
			log.Info(e)
			saveFileResult(rpt, db.RptStatusFail)
		} else {
			saveFileResult(rpt, db.RptStatusDownloaded)
		}
	})
	if err != nil {
		log.Info("download rpt file failed: %s", rpt.RptFileUrl)
		log.Info(err)
		saveFileResult(rpt, db.RptStatusFail)
	}
}

func saveFileResult(rpt db.AmazonRpt, status int) {
	rpt.Status = status
	_, err := app.GetOrm().Context.Update(&rpt)
	if err != nil {
		log.Info(err)
		return
	}
	log.Info("update rpt success[save rpt file]")
}
